//
// Created by 元穗 on 2017/7/17.
// Copyright (c) 2017 敬信. All rights reserved.
//

enum BarLocation: String {
    case Left
    case Mid
    case Right
}

public typealias OnNavItemClick = () -> ();

public class NavBar {
    
    let common_ic_back_white = "back_btn";
    let kMidTextMaxCount = 30;
    
    static var config: NavBarConfigure?;
    public var delegate: NavBarDelegate?
    weak var viewCon: UIViewController?;
    var item: UINavigationItem?;
    var tag = 0;
    public var scriptColor: UIColor = config!.scriptColor!;
    public var titleColor: UIColor = config!.titleColor!;
    
    var searchBar: UISearchBar = UISearchBar()
    
    lazy var viewClickMap: Dictionary<NSInteger, OnNavItemClick> = {
        return Dictionary<NSInteger, OnNavItemClick>();
    }();
    
    public class func initialize(_ config: NavBarConfigure) {
        self.config = config;
    }
    
    public init(_ viewCon: UIViewController) {
        self.viewCon = viewCon;
        self.navBackGroundColor((NavBar.config?.bgColor)!);
        item = viewCon.navigationItem;

        self.viewCon?.navigationController?.navigationBar.shadowImage =
            UIImage.setColor(App.config?.navBgColor!)
        
    }
    
    public func navBackGroundColor(_ color: UIColor) {
        self.viewCon?.navigationController?.navigationBar.barTintColor = color
    }
    
    /************************
     * 添加左边view
     ************************/
    /// FIXME: 不需要??
    public func addBackBtn(_ click: @escaping OnNavItemClick) {
        addLeftView(image: common_ic_back_white, click: click);
    }
    
    public func addBackBtn(image: String,_ click: @escaping OnNavItemClick) {
        addLeftView(image: image, click: click);
    }
    
    public func addLeftView(image: String, click: @escaping OnNavItemClick) {
        addLeftView(text: nil, image: image, click: click);
    }
    
    public func addLeftView(text: String?, image: String?, click: @escaping OnNavItemClick) {
        addView(location: .Left, text: text, textColor: nil, image: image, click: click);
    }
   
    /************************
     * 添加右边view
     ************************/
    public func addRightView(text: String) {
        addRightView(text: text, click: {});
    }
    
    public func addRightView(image: String) {
        addRightView(text: nil, image: image, click: {});
    }
    
    public func addRightView(text: String, image: String) {
        addRightView(text: text, image: image, click: {});
    }
    
    public func addRightView(text: String, click: @escaping OnNavItemClick) {
        addRightView(text: text, image: nil, click: click);
    }
    
    public func addRightView(text: String, textColor: UIColor, click: @escaping OnNavItemClick) {
//        addRightView(text: text, image: nil, click: click);
        addView(location: .Right, text: text, textColor: textColor, image: nil, click: click);
    }
    
    public func refreshButtonWithTag(tag: Int, image: String?, text: String?, canTouch: Bool, textColor: UIColor, alpha: CGFloat) {
        
        let leftArr = self.item?.leftBarButtonItems;
        let rightArr = self.item?.rightBarButtonItems;
        
        if leftArr != nil {
            for t in leftArr! {
                if t.customView?.tag == tag {
                    let btn = t.customView as! UIButton
                    btn.isUserInteractionEnabled = canTouch
                    btn.setTitleColor(textColor, for: .normal)
                    btn.titleLabel?.alpha = alpha
                    if image != nil {
                        btn.setImage(UIImage(named: image!), for: .normal)
                    } else {
                        btn.setImage(UIImage(), for: .normal)
                    }
                    
                    if text != nil {
                        btn.setTitle(text, for: .normal)
                    } else {
                        btn.setTitle("", for: .normal)
                    }
                }
            }
        }
        
        if rightArr != nil {
            for t in rightArr! {
                if t.customView?.tag == tag {
                    let btn = t.customView as! UIButton
                    btn.isUserInteractionEnabled = canTouch
                    btn.setTitleColor(textColor, for: .normal)
                    btn.titleLabel?.alpha = alpha
                    if image != nil {
                        btn.setImage(UIImage(named: image!), for: .normal)
                    } else {
                        btn.setImage(UIImage(), for: .normal)
                    }
                    
                    if text != nil {
                        btn.setTitle(text, for: .normal)
                    } else {
                        btn.setTitle("", for: .normal)
                    }
                }
            }
        }
    }
    
    //更新按钮文字
    public func refreshButtonWithTag(tag: Int, canTouch: Bool, textColor: UIColor, alpha: CGFloat) {
        let leftArr = self.item?.leftBarButtonItems;
        let rightArr = self.item?.rightBarButtonItems;
       
        if leftArr != nil {
            for t in leftArr! {
                if t.customView?.tag == tag {
                    let btn = t.customView as! UIButton
                    btn.isUserInteractionEnabled = canTouch
                    btn.setTitleColor(textColor, for: .normal)
                    btn.titleLabel?.alpha = alpha
                }
            }
        }
        
        if rightArr != nil {
            for t in rightArr! {
                if t.customView?.tag == tag {
                    let btn = t.customView as! UIButton
                    btn.isUserInteractionEnabled = canTouch
                    btn.setTitleColor(textColor, for: .normal)
                    btn.titleLabel?.alpha = alpha
                }
            }
        }
    }
    
    public func addRightView(image: String, click: @escaping OnNavItemClick) {
        addRightView(text: nil, image: image, click: click);
    }
    
    public func addRightView(text: String?, image: String?, click: @escaping OnNavItemClick) {
        addView(location: .Right, text: text, textColor: nil, image: image, click: click);
    }
    
    public func addRightView(text: String?, textColor: UIColor?, image: String?, click: @escaping OnNavItemClick) {
        addView(location: .Right, text: text, textColor: textColor, image: image, click: click);
    }
    
    /************************
     * 添加中间view
     ************************/
    public func addMidView(text: String) {
        addMidView(text: text, image: nil, click: {});
    }
    
    public func addMidView(text: String?, image: String?, click: @escaping OnNavItemClick) {
        addView(location: .Mid, text: text, textColor: nil, image: image, click: click);
    }
    
    /************************
     * 添加中间searchBar
     ************************/
    public func addMidSearchBar(placeHolder: String?, delegate: ViewConEx, bgColor: UIColor, textColor: UIColor, width: CGFloat, height: CGFloat) {
        addMidSearchBar(placeHolder: placeHolder,
                        leftImage: "",
                        clearImage: "",
                        bgColor: bgColor,
                        textColor: textColor,
                        width: width,
                        height: height,
                        clear: {},
                        delegate: delegate)
    }
    
    public func addMidSearchBar(placeHolder: String?,
                                leftImage: String?,
                                clearImage: String,
                                bgColor: UIColor,
                                textColor: UIColor,
                                width: CGFloat,
                                height: CGFloat,
                                clear: @escaping OnNavItemClick,
                                delegate: ViewConEx) {
        let bg = UIImage.setColor(bgColor, width: width, height: height)

        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
        titleView.backgroundColor = bgColor
        titleView.layer.cornerRadius = 17
        titleView.layer.masksToBounds = true
        
        searchBar.frame = CGRect.init(x: 0, y: 0, width: titleView.frame.size.width, height: titleView.frame.size.height)
        //添加空字符串让placeHolder左对齐
        searchBar.placeholder = placeHolder! + "                                              "
        searchBar.contentMode = .left
        searchBar.setSearchFieldBackgroundImage(bg, for: .normal)
        searchBar.delegate = delegate as? UISearchBarDelegate
        
        //设置文本框
        let searchField = searchBar.value(forKey: "_searchField") as? UITextField
        searchField?.textColor = UIColor.white
        searchField?.font = UIFont.systemFont(ofSize: 14)
        searchField?.setValue(UIColor.HexString("#9699A2"), forKeyPath: "_placeholderLabel.textColor")
        //设置文本左边的间距
        if #available(iOS 9.0, *){
            searchField?.leftView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 4, height: 0))
        }
        if #available(iOS 10.0, *){
            searchField?.leftView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 4, height: 0))
        }
//        //隐藏光标
//        searchField?.tintColor = UIColor.clear

//        let clearButton = UIButton(type: .custom)
//        clearButton.setImage(UIImage(named: "clear_textField"), for: .normal)
//        clearButton.frame = CGRect(x: -20, y: 0, width: 50, height: 14)
//        clearButton.contentMode = .scaleAspectFit
//        clearButton.addTarget(self, action: #selector(UITextField.clear(sender:)), for: .touchUpInside)
//        searchField?.rightView = clearButton
//
//        searchField?.rightViewMode = .always
//        searchField?.clearButtonMode = .whileEditing;
        searchField?.rightView = UIView.init(frame: CGRect.init(x: searchBar.frame.size.width - 4, y: 0, width: 4, height: 0))

        titleView.addSubview(searchBar)
        self.item?.titleView = titleView
    }
    
    func clear(sender: UIButton) {
        searchBar.text = ""
    }
    
    private func addView(location: BarLocation, text: String?, textColor: UIColor?, image: String?, click: @escaping OnNavItemClick) {
        var items = [UIBarButtonItem]();
        let fixItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil);
        fixItem.width = (NavBar.config?.edgeSpace)!;
        
        if (location == .Left) {
            let arr = self.item?.leftBarButtonItems;
            if arr != nil {
                for bar in arr! {
                    items.append(bar);
                }
            } else {
                //                items.append(fixItem);
            }
        } else {
            let arr = self.item?.rightBarButtonItems;
            if arr != nil {
                for bar in arr! {
                    items.append(bar);
                }
            } else {
                //                items.append(fixItem);
            }
        }
        
        let btn = UIButton(type: .custom);
        
        // 设置图片
        if image != nil {
            if location == .Left {
                btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
            } else if location == .Right {
                btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right
            }
            btn.setImage(UIImage(named: image!), for: .normal);
        }
        
        // 设置文本
        if text != nil {
            if location == .Mid {
                if text!.characters.count > kMidTextMaxCount {
                    let index = text!.index(text!.startIndex, offsetBy: kMidTextMaxCount, limitedBy: text!.endIndex)
                    var title = text!.substring(to: index!);
                    title.append("...")
                    btn.setTitle(title, for: UIControlState.normal);
                } else {
                    btn.setTitle(text, for: UIControlState.normal);
                }
                
                btn.titleLabel?.font = (NavBar.config?.titleFont)!;
                btn.frame = adjustsFontSizeToFitWidth(text: text!, font: (NavBar.config?.titleFont)!, textType: true);
                if textColor != nil {
                    btn.setTitleColor(textColor, for: UIControlState.normal);
                } else {
                    btn.setTitleColor(titleColor, for: UIControlState.normal);
                }
                
            } else {
                btn.setTitle(text, for: UIControlState.normal);
                btn.titleLabel?.font = (NavBar.config?.scriptFont)!;
                btn.frame = adjustsFontSizeToFitWidth(text: text!, font: (NavBar.config?.scriptFont)!, textType: true);
                if textColor != nil {
                    btn.setTitleColor(textColor, for: UIControlState.normal);
                } else {
                    btn.setTitleColor(scriptColor, for: UIControlState.normal);
                }
                
            }
            btn.sizeToFit();
            
            
        } else {
            btn.frame = (NavBar.config?.imageCoordinate)!;
        }
        
        btn.addTarget(self, action: #selector(didPressBarButton(_:)), for: .touchUpInside);
        tag += 1;
        btn.tag = tag;
        viewClickMap.updateValue(click, forKey: tag);
        
        switch location {
        case .Left:
            let barItem = UIBarButtonItem(customView: btn);
            items.append(barItem);
            items.append(fixItem);
            self.item?.leftBarButtonItems = items;
            
            break;
        case .Mid:
            self.item?.titleView = btn;
            break;
        case .Right:
            let barItem = UIBarButtonItem(customView: btn);
            items.append(barItem);
            items.append(fixItem);
            self.item?.rightBarButtonItems = items;
            
            break;
        }
    }
    
    /// 点击事件
    @objc func didPressBarButton(_ button: UIButton) {
        print("........tag:", button.tag);
        viewClickMap[button.tag]!();
        
        //        delegate?.didClickBarButton(didClickBarButton: self, aTag: button.tag);
    }
    
    /// 自适应宽度
    private func adjustsFontSizeToFitWidth(text: String, font: UIFont, textType: Bool) -> CGRect {
        let size = CGSize(width: 240, height: (NavBar.config?.height)!);
        let textSize = text.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil).size;
        if (textType) {
            return CGRect(x: 0, y: 0, width: textSize.width + 25, height: textSize.height);
        } else {
            return CGRect(x: 0, y: 0, width: textSize.width, height: textSize.height);
        }
    }
}

/// 事件协议

public protocol NavBarDelegate: NSObjectProtocol {
    func didClickBarButton(didClickBarButton: NavBar, aTag: NSInteger)
}

